package com.zhaoqi.hr.repository;

import com.zhaoqi.hr.entity.WorkContract;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 工作合同数据访问层
 */
@Repository
public interface WorkContractRepository extends JpaRepository<WorkContract, Long>, JpaSpecificationExecutor<WorkContract> {

    /**
     * 根据合同编号查找合同
     */
    Optional<WorkContract> findByContractNumber(String contractNumber);

    /**
     * 根据岗位申请ID查找合同
     */
    boolean existsByJobApplicationId(Long jobApplicationId);

    /**
     * 根据雇主ID查找合同（按创建时间倒序）
     */
    List<WorkContract> findByEmployer_User_IdOrderByCreatedAtDesc(Long employerId);

    /**
     * 根据劳动者ID查找合同（按创建时间倒序）
     */
    List<WorkContract> findByWorker_User_IdOrderByCreatedAtDesc(Long workerId);

    /**
     * 根据合同状态查找
     */
    List<WorkContract> findByStatus(WorkContract.ContractStatus status);

    /**
     * 查找待签署的合同
     */
    @Query("SELECT c FROM WorkContract c WHERE c.status = 'PENDING_SIGN'")
    List<WorkContract> findPendingSignContracts();

    /**
     * 查找履行中的合同
     */
    @Query("SELECT c FROM WorkContract c WHERE c.status = 'ACTIVE' AND c.startTime <= :now AND (c.endTime IS NULL OR c.endTime > :now)")
    List<WorkContract> findActiveContracts(@Param("now") LocalDateTime now);

    /**
     * 查找即将到期的合同
     */
    @Query("SELECT c FROM WorkContract c WHERE c.status = 'ACTIVE' AND c.endTime BETWEEN :now AND :expireTime")
    List<WorkContract> findExpiringContracts(@Param("now") LocalDateTime now, 
                                             @Param("expireTime") LocalDateTime expireTime);

    /**
     * 统计合同签署情况
     */
    @Query("SELECT c.status, COUNT(c) FROM WorkContract c GROUP BY c.status")
    List<Object[]> countByStatus();

    /**
     * 查找第三方合同ID
     */
    Optional<WorkContract> findByThirdPartyContractId(String thirdPartyContractId);

    /**
     * 根据雇主ID统计合同数量
     */
    long countByEmployer_User_Id(Long employerId);

    /**
     * 根据劳动者ID统计合同数量
     */
    long countByWorker_User_Id(Long workerId);

    /**
     * 根据状态统计合同数量
     */
    long countByStatus(WorkContract.ContractStatus status);
}
